package View;

import Controller.ReservationController;
import Model.TestData;
import java.awt.BorderLayout;
import java.beans.PropertyChangeEvent;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import javax.swing.*;
import javax.swing.text.MaskFormatter;
import javax.swing.table.DefaultTableModel;

public class CreerReservation extends AbstractViewPanel  {

    //variables
    private ReservationController controller;
    /**
     * Creates new form CreerReservation
     */
    public CreerReservation(ReservationController controller) {
        
        this.controller = controller;
        
        initComponents();
        
        String[][] ligneReservation = {{"","","",""}};
        populerTable(ligneReservation);
        //this.jtblLigneReservation.setColumnModel(new TableColumnModel());
    }
    

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        lblDateDebut = new javax.swing.JLabel();
        lblDateFin = new javax.swing.JLabel();
        lblCat = new javax.swing.JLabel();
        lblNb = new javax.swing.JLabel();
        btnCancel = new javax.swing.JButton();
        btnEnregistrer = new javax.swing.JButton();
        cboCategorie = new javax.swing.JComboBox();
        MaskFormatter mf = null; 
        try {
            mf = new MaskFormatter("##/##/####");
            mf.setPlaceholderCharacter('_');
        } catch (Exception e) {
            e.printStackTrace();
        }
        txtDteDebut = new JFormattedTextField(mf);
        txtDteFin = new JFormattedTextField(mf);
        ReinitialiserChamps();
        btnOK = new javax.swing.JButton();
        jspnNbChambre = new javax.swing.JSpinner();
        jScrollPane1 = new javax.swing.JScrollPane();
        tblLigneReservation = new javax.swing.JTable();
        btnSupprimer = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();

        lblDateDebut.setText("Date Début:");

        lblDateFin.setText("Date de fin:");

        lblCat.setText("Catégorie:");

        lblNb.setText("Nombre de chambres:");

        btnCancel.setText("Annuller");
        btnCancel.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                btnCancelMouseClicked(evt);
            }
        });
        btnCancel.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCancelActionPerformed(evt);
            }
        });

        btnEnregistrer.setText("Enregistrer");
        btnEnregistrer.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                btnEnregistrerMouseClicked(evt);
            }
        });

        cboCategorie.setModel(new DefaultComboBoxModel(TestData.getNomCategorie()));

        btnOK.setText("Ajouter les Chambres");
        btnOK.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                btnOKMouseClicked(evt);
            }
        });

        tblLigneReservation.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        jScrollPane1.setViewportView(tblLigneReservation);

        btnSupprimer.setText("Supprimer Chambre");
        btnSupprimer.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                btnSupprimerMouseClicked(evt);
            }
        });
        btnSupprimer.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSupprimerActionPerformed(evt);
            }
        });

        jLabel1.setText("DD/MM/YYYY");

        jLabel2.setText("DD/MM/YYYY");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(48, 48, 48)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 563, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(150, 150, 150)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addGap(123, 123, 123)
                                .addComponent(btnOK))
                            .addGroup(layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                    .addComponent(lblDateFin)
                                    .addComponent(lblDateDebut)
                                    .addComponent(lblCat)
                                    .addComponent(lblNb))
                                .addGap(26, 26, 26)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                    .addComponent(txtDteDebut)
                                    .addComponent(txtDteFin)
                                    .addComponent(cboCategorie, javax.swing.GroupLayout.PREFERRED_SIZE, 106, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(jspnNbChambre, javax.swing.GroupLayout.PREFERRED_SIZE, 57, javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addGap(18, 18, 18)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jLabel2)
                                    .addComponent(jLabel1))))))
                .addContainerGap(49, Short.MAX_VALUE))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addGap(0, 0, Short.MAX_VALUE)
                .addComponent(btnSupprimer)
                .addGap(18, 18, 18)
                .addComponent(btnEnregistrer, javax.swing.GroupLayout.PREFERRED_SIZE, 113, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(btnCancel)
                .addGap(152, 152, 152))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(31, 31, 31)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtDteDebut, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(lblDateDebut)
                    .addComponent(jLabel1))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtDteFin, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(lblDateFin)
                    .addComponent(jLabel2))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(cboCategorie, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(lblCat))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblNb)
                    .addComponent(jspnNbChambre, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(btnOK)
                .addGap(29, 29, 29)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 127, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnEnregistrer)
                    .addComponent(btnCancel)
                    .addComponent(btnSupprimer))
                .addContainerGap(34, Short.MAX_VALUE))
        );
    }// </editor-fold>//GEN-END:initComponents

    private void btnEnregistrerMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btnEnregistrerMouseClicked
        
        boolean afficherConfirmation = true;
        int ajouterResEnCours = 0;
        if(!"".equals(this.txtDteDebut.getValue().toString()) && !"".equals(this.txtDteFin.getValue().toString())){
            ajouterResEnCours = JOptionPane.showConfirmDialog(this,
                                 "Voulez-vous ajouter la réservation de la chambre en cours à la réservation?", "réservation d'une chambre en cours",
                                 JOptionPane.YES_NO_OPTION);
                   
            if(ajouterResEnCours == 0)
            {    
                boolean ligneAjoute = ajouterLigneReservation();
                if(!ligneAjoute)
                {
                    afficherConfirmation = false;
                }
            }else{
                if(this.tblLigneReservation.getRowCount() == 0)
                    afficherConfirmation = false;
            }
        }else{
            afficherConfirmation = false;
        }
       
        
        if(afficherConfirmation || this.tblLigneReservation.getRowCount() != 0)
        {
            //afficher la nouvelle Interface
            ConfirmerReservation view = new ConfirmerReservation(controller);
            
            controller.addView(view);
            
            view.updateLigneReservation();
            
            JFrame displayFrame = new JFrame("Payer la réservation");
            displayFrame.getContentPane().add(view, BorderLayout.CENTER);
            displayFrame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
            displayFrame.pack();
            displayFrame.setVisible(true);
            
            this.getTopLevelAncestor().setVisible(false);
        }
    }//GEN-LAST:event_btnEnregistrerMouseClicked

    private void btnOKMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btnOKMouseClicked
        boolean ligneAjoute = ajouterLigneReservation();
        if(ligneAjoute == true){
            ReinitialiserChamps();
        }
    }//GEN-LAST:event_btnOKMouseClicked

    private void btnCancelMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btnCancelMouseClicked
        controller.deleteReservation();
        this.getTopLevelAncestor().setVisible(false);
    }//GEN-LAST:event_btnCancelMouseClicked

    private void btnCancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_btnCancelActionPerformed

    private void btnSupprimerMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btnSupprimerMouseClicked
        DefaultTableModel model = (DefaultTableModel)tblLigneReservation.getModel();
        int[] rows = tblLigneReservation.getSelectedRows();
        for(int i=0;i<rows.length;i++){
           model.removeRow(rows[i]-i);
         
        }
    }//GEN-LAST:event_btnSupprimerMouseClicked

    private void btnSupprimerActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSupprimerActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_btnSupprimerActionPerformed
    
    private void ReinitialiserChamps(){
        MaskFormatter mf = null;
        try {
            mf = new MaskFormatter("##/##/####");
            mf.setPlaceholderCharacter('_');
        } catch (Exception e) {
            e.printStackTrace();
        }
        
        txtDteDebut.setValue("");
        txtDteFin.setValue("");
        if(this.cboCategorie.getItemAt(0)!= null)
            this.cboCategorie.setSelectedIndex(0);
        //populerTable();
    }
    
    private void populerTable(String[][] ligneReservation){
        
        String[] celNames;
        
        celNames = new String[4];
        celNames[0] = "Nombre de chambre";
        celNames[1] = "Nom de la catégorie";
        celNames[2] = "Date d'arrivée";
        celNames[3] = "Date de départ";
        
        JTable jtbl = new JTable(ligneReservation, celNames);
        this.tblLigneReservation.setModel(new DefaultTableModel());
        this.tblLigneReservation.setModel(jtbl.getModel());        
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnCancel;
    private javax.swing.JButton btnEnregistrer;
    private javax.swing.JButton btnOK;
    private javax.swing.JButton btnSupprimer;
    private javax.swing.JComboBox cboCategorie;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JSpinner jspnNbChambre;
    private javax.swing.JLabel lblCat;
    private javax.swing.JLabel lblDateDebut;
    private javax.swing.JLabel lblDateFin;
    private javax.swing.JLabel lblNb;
    private javax.swing.JTable tblLigneReservation;
    private javax.swing.JFormattedTextField txtDteDebut;
    private javax.swing.JFormattedTextField txtDteFin;
    // End of variables declaration//GEN-END:variables

    @Override
    public void modelPropertyChange(PropertyChangeEvent evt) {
        
        switch(evt.getPropertyName()){
            case ReservationController.NUM_CONFIRMATION_PROPERTY:
                //the num of confirmation has been attributed to the reservation so its finished.
                this.getTopLevelAncestor().setVisible(false);
                break;
            case ReservationController.LIGNE_RESERVATION_PROPERTY:
                populerTable((String[][])evt.getNewValue());
                break;
            case ReservationController.NOT_ENOUGH_PLACE_EVENT:
                ChoisirChambre vueChoisirChambre = new ChoisirChambre(this, controller, getDate(this.txtDteDebut.getText()), getDate(this.txtDteDebut.getText()));
                controller.addView(vueChoisirChambre);
                
                JFrame displayFrame = new JFrame("Pas assez de chambre libre");
                displayFrame.getContentPane().add(vueChoisirChambre, BorderLayout.CENTER);
                displayFrame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
                displayFrame.pack();
                
                displayFrame.setVisible(true);
                break;
            case ReservationController.CLIENT_PROPERTY:
                this.getTopLevelAncestor().setVisible(false);
                break;
        }
    }

    private boolean ajouterLigneReservation() {
        boolean ligneAjoutee = true;
        try{
            Date dteFin;
            Date dteDebut;
            
            SimpleDateFormat dateFormat = new SimpleDateFormat("dd/mm/yyyy"); 
            dateFormat.setLenient(false);
            
            dteDebut = getDate(this.txtDteDebut.getText());
                        
            if(dteDebut != null){
                dteFin = getDate(this.txtDteFin.getText());
                 
                if(dteFin!= null && dteDebut.after(dteFin)){
                    JOptionPane.showMessageDialog(this, "Vous ne pouvez pas avoir une date de début après la date de fin", "Date de fin avant la date de début", 0);
                    ligneAjoutee = false;
                }
                if(ligneAjoutee){
                    int qte = Integer.parseInt(this.jspnNbChambre.getValue().toString());

                    String categorie = this.cboCategorie.getSelectedItem().toString();
                    
                    controller.addLigneReservation(categorie, qte, dteDebut, dteFin);
                }
            }
        }catch(NumberFormatException e){
            if(ligneAjoutee){
                JOptionPane.showMessageDialog(this, "Une erreur c'est produite lors de l'enregistrement\n"
                    + "de la réservation. Veuillez vous assurez que les\n"
                    + "informations entrées sont correctes.", "Une erreur s'est produite", 0);
                ligneAjoutee = false;
            }
        }
        return ligneAjoutee;
    }
    private Date getDate(String date){
        Date now = Calendar.getInstance().getTime();
        Date dteFormatte = new Date();
        boolean isRealDate = true;
        
        SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy"); 
        dateFormat.setLenient(false);
        
        try{
            dteFormatte = dateFormat.parse(date);
        }catch (ParseException e){
            JOptionPane.showMessageDialog(this, "Veuillez entré une date du format dd/MM/yyyy.", "La date entré n'est pas bonne", 0);
            isRealDate = false;
        }
        if(isRealDate){
            if(dteFormatte.before(now)){
                isRealDate = false;
                JOptionPane.showMessageDialog(this, "Veuillez entré une date après aujourd'hui", "La date entré n'est pas bonne", 0);
            }
        }
        if(isRealDate){
            return dteFormatte;
        }else
            return null;
    }
    
    public void changeCategorie(int indexCategorie){
        cboCategorie.setSelectedIndex(indexCategorie);
    }
}
